package com.uchiha.nova.core.tool.util;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.function.Supplier;

/**
 * @author 周林静
 * @Date 2022-01-01 9:01
 * @Version 1.0
 */
@Component
public class OrderLockUtil {

    @Resource
    private CommonRedisHelper commonRedisHelper;


    public final static  String PREFIX_LOCK_ORDER_SUBMIT = ":lock_OrderSubmit:";
    public final static  String PREFIX_LOCK_ORDER_REFUND = ":lock_OrderRefund:";

    // 校验并更新库存
    public Boolean updateGoodInventory(Long id, Supplier<Object> execute, String lockName){
        String x = lockName+id;
        boolean lock = commonRedisHelper.lock(x);
        if(lock){
            Object a= execute.get();
            int i = 0;
            if(a instanceof Integer){
                i = (int) a;
            }else if(a instanceof Boolean){
                if ((boolean)a) {
                    i = 1;
                }
            }
            if(1==i){
                commonRedisHelper.delete(x);
                return true;
            }else{
                commonRedisHelper.delete(x);
                return false;
            }

        }else{
            // 设置失败次数计数器, 当到达5次时, 返回失败
            int failCount = 1;
            while(failCount <= 5){
                // 等待100ms重试
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (commonRedisHelper.lock(x)){
                    Object a= execute.get();
                    int i = 0;
                    if(a instanceof Integer){
                        i = (int) a;
                    }else if(a instanceof Boolean){
                        if ((boolean)a) {
                            i = 1;
                        }
                    }
                    if(1==i){
                        commonRedisHelper.delete(x);
                        return true;
                    }else{
                        commonRedisHelper.delete(x);
                        return false;
                    }
                }else{
                    failCount ++;
                }
            }
            return false;
        }
    }
}
